#define _CRT_SECURE_NO_WARNINGS 1

#include "singleList.h"

void singleListPrint(struct Node* phead)
{
	if (phead == NULL)
	{
		printf("NULL\n");
	}
	struct Node* tmp = NULL;
	tmp = phead;
	while (tmp != NULL)
	{
		printf("%d ", tmp->val);
		tmp = tmp->next;
	}
	printf("\n");
}

void singleListPriRan(struct Node* phead)
{
	if (phead == NULL)
	{
		printf("NULL\n");
	}
	struct Node* tmp = NULL;
	tmp = phead;
	while (tmp != NULL)
	{
		printf("%d ", tmp->val);
		tmp = tmp->random;
	}
	printf("\n");
}


struct Node* copyRandomList(struct Node* head)
{
	struct Node* cur = head;
	if (cur == NULL)
	{
		return cur;
	}
	struct Node* next = head->next;
	if (next == NULL)
	{
		struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
		newnode->next = head->next;
		if (head->random != NULL)
		{
			newnode->random = newnode;
		}
		else
		{
			newnode->random = NULL;
		}
		newnode->val = head->val;
		return newnode;
	}
	while (cur)
	{
		struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
		newnode->random = NULL;
		cur->next = newnode;
		newnode->val = cur->val;
		newnode->next = next;
		cur = next;
		if (next != NULL)
		{
			next = next->next;
		}
	}
	cur = head;
	next = head->next;
	while (cur)
	{
		if (cur->random != NULL)
		{
			next->random = cur->random->next;
		}
		else
		{
			next->random = cur->random;
		}
		cur = cur->next->next;
		if (next->next != NULL)
		{
			next = next->next->next;
		}
	}
	cur = head->next;
	next = cur->next->next;
	while (cur->next)
	{
		cur->next = next;
		cur = next;
		if (next->next != NULL)
		{
			next = next->next->next;
		}
	}
	return head->next;
}